<?php

namespace App\Http\Traits;

use Illuminate\Http\JsonResponse;

trait ResponseTrait
{

    public function successful($msg = 'ok', $data = null): JsonResponse
    {
        if (!is_null($data)) return $this->make(200, $msg, $data);
        if (!is_string($msg)) return $this->make(200, 'ok', $msg);
        return $this->make(200, $msg);
    }

    public function fail($code, $msg = 'error', $data = null): JsonResponse
    {
        if (!is_null($data)) return $this->make($code, $msg, $data);
        if (is_string($code)) return $this->make(500, $code);
        return $this->make($code, $msg);
    }


    public function make($code, $msg, $data = null): JsonResponse
    {
        $resp = compact('code', 'msg');
        if (!is_null($data)) $resp['data'] = $data;
        return response()->json($resp);
    }

    public function getResponseData($response): array
    {
        return json_decode($response->content(), true)['data'];
    }
}
